package top.winshu.common.util;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

/**
 * @author winshu
 * @since 2022/5/25
 **/
public class MemoryUtil {

    /**
     * 将字节长度转换为人类可读
     */
    public static String humanLength(long length) {
        long absB = length == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(length);
        if (absB < 1024) {
            return length + "B";
        }
        long value = absB;
        CharacterIterator ci = new StringCharacterIterator("KMGTPE");
        for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
            value >>= 10;
            ci.next();
        }
        value *= Long.signum(length);
        return String.format("%.1f%cB", value / 1024.0, ci.current());
    }
}
